package com.lqwu.mallchatserver.common.event.listener;

import com.lqwu.mallchatserver.common.event.UserBlackEvent;
import com.lqwu.mallchatserver.common.event.UserOnlineEvent;
import com.lqwu.mallchatserver.common.event.UserRegisterEvent;
import com.lqwu.mallchatserver.user.model.entry.User;
import com.lqwu.mallchatserver.user.model.enums.UserStatusEnum;
import com.lqwu.mallchatserver.user.service.IpService;
import com.lqwu.mallchatserver.user.service.UserService;
import com.lqwu.mallchatserver.user.service.cache.UserCache;
import com.lqwu.mallchatserver.websocket.service.WebSocketService;
import com.lqwu.mallchatserver.websocket.service.adapter.WebSocketAdapter;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * 用户拉黑监听器
 */
@Component
public class UserBlackListener {
    @Resource
    private UserService userService;
    @Resource
    private WebSocketService webSocketService;
    @Resource
    public UserCache userCache;

    /**
     * 发送消息给前端
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class,phase = TransactionPhase.AFTER_COMMIT)
    public void sendMsg(UserBlackEvent event) {
        webSocketService.sendToAllOnline(WebSocketAdapter.buildBlack(event.getUser()));
    }

    /**
     * 改变用户状态
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class,phase = TransactionPhase.AFTER_COMMIT)
    public void changeUserStatus(UserBlackEvent event) {
        userService.lambdaUpdate().eq(User::getId,event.getUser().getId())
                .set(User::getStatus, UserStatusEnum.BLACK.getId())
                .update();
    }

    /**
     * 删除缓存
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class,phase = TransactionPhase.AFTER_COMMIT)
    public void evictCache(UserBlackEvent event) {
        userCache.evictBlackMap();
    }
}
